﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls; 

using CARMSBusiness;

namespace CARMS
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                txtUserName.Focus();
                txtUserName.Text = "admin";
                txtPassword.Attributes.Add("value","admin");
            }
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (txtUserName.Text.Trim().Length == 0)
            {
                lblMessage.Text = "Please input user name.";
                return;
            }
            if (txtPassword.Text.Trim().Length == 0)
            {
                lblMessage.Text = "Please input password.";
                return;
            }
            string userName = txtUserName.Text.Trim();

            var VistorIP = Request.UserHostAddress;
            var userData = SecurityBusiness.ValidateUser(userName, txtPassword.Text.Trim(), Session.SessionID, VistorIP);
            if (userData!=null)
            {
                FormsAuthentication.SetAuthCookie(userData.UserId.ToString(), true);
                Session["CurrentLoginUser"]=new UserData
                                                {
                                                     LoginName=userData.LoginName,
                                                      UserID=userData.UserId,
                                                      UserName=userData.FullName,
                                                  
                                                };
                SetCookieUserID(userData.UserId);
                Response.Redirect("~/default.aspx");
            }
            else
            {
                lblMessage.Text = "Sorry, the user name or password was incorrect.";
                return;
            }
        }

        public void SetCookieUserID(int userID)
        {
            HttpCookie cookie = Request.Cookies.Get("LIMSUserInfo");
            if (cookie != null)
            {
                cookie.Values["UserID"] = userID.ToString();
                cookie.Value = userID.ToString();
                cookie.Expires = DateTime.Now.AddDays(30);
                Response.Cookies.Add(cookie);
            }
            else
            { 
                cookie = new HttpCookie("LIMSUserInfo");
                cookie.Value = userID.ToString();
                cookie.Expires = DateTime.Now.AddDays(30);
                cookie.Values.Add("UserID", userID.ToString());
                Response.Cookies.Add(cookie);
            }

        }

    }
}
